<template>
    <div ref="wrapper">
        <div class="box">
            <div v-show="loadingup" class="loading">
                <img class="img" src="./loading.gif">
                <div class="text">正在更新</div>
            </div>
            <slot></slot>
            <div v-show="loadingdown" class="loading">
                <img class="img" src="./loading.gif">
                <div class="text">正在加载</div>
            </div>
        </div>
    </div>
</template>

<script type="text/ecamscript-6">
import BScroll from "better-scroll";
export default {
  props: {
    probeType: {
      type: Number,
      default: 2
    },
    click: {
      type: Boolean,
      default: true
    },
    data: {
      type: Array,
      default: null
    },
    pullup: {
      type: Boolean,
      default: false
    },
    pulldown: {
      type: Boolean,
      default: false
    }
  },
  mounted() {
    this.$nextTick(() => {
      this._initScroll();
    });
  },
  data() {
    return {
      loadingup: false,
      loadingdown: false
    };
  },
  methods: {
    _initScroll() {
      if (!this.$refs.wrapper) {
        return;
      }
      this.scroll = new BScroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click
      });
      if (this.pulldown) {
        this.scroll.on("touchEnd", (pos) => {
          if (pos.y <= (this.scroll.maxScrollY-50)) {
            this.loadingdown = true;
            this.$emit("scrollToEnd");
            this.$nextTick(() => {
              this.refresh();
              this.scroll.scrollTo(0,this.scroll.maxScrollY)
            });
          }
        });
      }
      if (this.pullup) {
        this.scroll.on("touchEnd", pos => {
          if (pos.y > 50) {
            this.loadingup = true;
            this.$emit("scrollToTop");
            this.$nextTick(() => {
              this.refresh();
            });
          }
        });
      }
    },
    refresh() {
      this.scroll && this.scroll.refresh();
    },
    loadingupFinish() {
      this.loadingup = false;
      this.$nextTick(() => {
        this.refresh();
      });
    },
    loadingdownFinish() {
      this.loadingdown = false;
      this.$nextTick(() => {
        this.refresh();
      });
    }
  },
  watch: {
    data() {
      this.$nextTick(() => {
        this.refresh();
      });
    }
  }
};
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
.box
    overflow hidden
    .loading
        display flex
        justify-content center
        align-items center
        margin 10px 0
        .img
            flex 0 0 20px
            height 20px
        .text
            color #ccc
            font-size 16px
</style>

